package com.ehotting.edsta.signalAnalysis.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ehotting.eaf.core.domain.R;
import com.ehotting.eaf.security.service.TokenService;
import com.ehotting.edsta.common.log.annotation.Log;
import com.ehotting.edsta.common.log.enums.BusinessType;
import com.ehotting.edsta.mqbd.signal.api.bean.MqSignalTcpData;
import com.ehotting.edsta.mqbd.signal.api.domain.netty.CallSimulateRequest;
import com.ehotting.edsta.mqbd.signal.api.domain.netty.LogPushRequest;
import com.ehotting.edsta.mqbd.signal.api.domain.netty.StopSimulateRequest;
import com.ehotting.mqbd.api.bean.MQDataAble;
import com.ehotting.mqbd.api.bean.MqApplicationContext;
import com.ehotting.mqbd.api.enums.SendTypeEnum;
import com.ehotting.mqbd.api.enums.TopicEnum;
import com.ehotting.mqbd.core.service.MQService;
import com.ehotting.mqbd.core.manager.AgentLinkManager;
import com.ehotting.mqbd.core.web.MqWebHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.FutureTask;

@Slf4j
@RestController
@RequestMapping("/baseService")
@Api(tags = "SignalAnalysisController", description = "中控系统调用仿真计算")
public class SignalAnalysisController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private MqApplicationContext mqApplicationContext;
    @Autowired
    private MQService mqService;
    @Autowired
    private AgentLinkManager agentLinkManager;
    @Autowired
    private SignalAnalysisWsController signalAnalysisWsController;




    @Log(title = "信号完整性分析", businessType = BusinessType.OTHER)
    @ApiOperation("获取信号分析仿真结果")
    @PostMapping("/getAnalysisResult")
    public R<String> getAnalysisResult(@RequestBody JSONObject jsonObject) {
        Long userId = tokenService.getLoginUser().getUserid();
        jsonObject.put("userId", userId);
        String mainProjectId = null;
        if (jsonObject.containsKey("mainProjectId")){
            mainProjectId = jsonObject.get("mainProjectId").toString();
        }

        // 创建请求，设置立创json参数
        CallSimulateRequest request = new CallSimulateRequest();
        request.setJsonData(jsonObject);

        String agentId = agentLinkManager.genAgentId(mqApplicationContext.getModule(),userId,mainProjectId);

        // 创建rocket mq请求
        MqSignalTcpData signalTcpData = MqSignalTcpData.create(TopicEnum.BLOCK, mqApplicationContext,agentId
                ,"");
        signalTcpData.setRequest(request);
        signalTcpData.setSync(true);
        signalTcpData.setSendType(new SendTypeEnum[]{SendTypeEnum.REDIS_REQUEST_BODY} );
        FutureTask<MQDataAble>  futureTask =  mqService.requestFuture(signalTcpData,10);

        sendWebsocket(signalTcpData,agentId);

        return MqWebHelper.handleResult( futureTask, signalTcpData);
    }

    @ApiOperation("停止仿真")
    @GetMapping("/stopSimulate/{mainProjectId}")
    public R<String> stopSimulate(@PathVariable("mainProjectId") @ApiParam("主程序工程id") Long mainProjectId){
        Long userId = tokenService.getLoginUser().getUserid();
        String agentId = agentLinkManager.genAgentId(mqApplicationContext.getModule(),userId,String.valueOf(mainProjectId));
        StopSimulateRequest data = new StopSimulateRequest();
        data.setMainProjectId(mainProjectId);
        data.setUserId(userId);

        MqSignalTcpData signalTcpData = MqSignalTcpData.create(TopicEnum.CONCURRENCY, mqApplicationContext, agentId,"");
        signalTcpData.setRequest(data);
        mqService.request(signalTcpData,10);
        return R.ok(signalTcpData.getMsg());
    }

    private void sendWebsocket(MqSignalTcpData signalTcpData,String agentId){
        log.info("Start sendWebsocket.");
        log.info("agentId:{},msg:{}",agentId,signalTcpData.getMsg());
        LogPushRequest logPushRequest = new LogPushRequest(agentLinkManager.getUserId(agentId),agentLinkManager.getProjectId(agentId),signalTcpData.getMsg());
        try {
            signalAnalysisWsController.sendUserMessage(JSON.toJSONString(logPushRequest),agentId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("Finish sendWebsocket. agentId:{}",agentId);
    }

}
